package com.zcs.app.lucky.ui

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.widget.ImageView
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import cn.sxw.android.base.adapter.CommonRecyclerAdapter
import cn.sxw.android.base.dialog.CustomDialogHelper
import cn.sxw.android.base.kt.BaseViewModel
import cn.sxw.android.base.utils.GlideStaticUtils
import cn.sxw.android.base.utils.RandomNameProvider
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.safframework.delegate.extras.extraDelegate
import com.zcs.app.lucky.BuildConfig
import com.zcs.app.lucky.R
import com.zcs.app.lucky.base.BaseLuckyActivity
import com.zcs.app.lucky.data.GroupDataCache
import com.zcs.app.lucky.databinding.ActivityCreateGroupBinding
import com.zcs.app.lucky.databinding.DialogAddPeopleBinding
import com.zcs.app.lucky.databinding.DialogSaveGroupBinding
import com.zcs.app.lucky.entity.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.util.*

@SuppressLint("RestrictedApi")
class CreateGroupActivity : BaseLuckyActivity<ActivityCreateGroupBinding, BaseViewModel>() {
    companion object {
        const val KEY_GROUP_ID = "KEY_GROUP_ID"
    }

    private var mAdapter: CommonRecyclerAdapter<LuckyPeople>? = null
    private val mItems = ArrayList<LuckyPeople>()
    private val mGroupId: String by extraDelegate(KEY_GROUP_ID, "")
    private val mGroup by lazy {
        GroupDataCache.findGroupById(mGroupId)
    }

    private fun isModify(): Boolean = !TextUtils.isEmpty(mGroupId)

    // 懒加载机制
    override fun onReady() {
        binding.toolbar.tvToolbarTitle.text = if (isModify()) "编辑分组" else "新建分组"
        binding.loadingLayout.visibility = View.VISIBLE
        binding.toolbar.tvToolbarRight.text = "保存"
    }

    override fun onInit() {
        initView()
    }

    override fun initObserve() {
    }

    override fun initData() {
        mItems.clear()
        if (isModify()) {
            mItems.addAll(mGroup.list)
        }
        // 尾部追加
        mItems.add(LuckyPeople(TYPE_USER_ADD))
        initAdapter()
        hideLoading()
    }

    private fun initAdapter() {
        if (mAdapter == null) {
            mAdapter =
                object : CommonRecyclerAdapter<LuckyPeople>(R.layout.item_lucky_people, mItems) {
                    override fun convert(holder: BaseViewHolder, item: LuckyPeople) {
                        val ivAvatar = holder.getView<ImageView>(R.id.ivAvatar)
                        val ivDelete = holder.getView<ImageView>(R.id.ivDelete)
                        val ivAdd = holder.getView<ImageView>(R.id.ivAdd)
                        holder.setVisible(R.id.ivAdd, item.isAdd())
                        holder.setVisible(R.id.ivDelete, !item.isAdd())
                        if (item.isAdd()) {
                            holder.setText(R.id.tvName, "添加")
                            ivAvatar.setImageResource(0)
                            ivAdd.setOnClickListener {
                                // onAddClick()
                                addResultLauncher.launch(
                                    Intent(
                                        this@CreateGroupActivity,
                                        AddPeopleActivity::class.java
                                    )
                                )
                            }
                        } else {
                            GlideStaticUtils.displayCircleImage(
                                item.avatar,
                                R.mipmap.ic_launcher_round,
                                ivAvatar
                            )
                            holder.setText(R.id.tvName, item.name)
                        }
                        // 添加移除功能
                        ivDelete.setOnClickListener {
                            CustomDialogHelper.showCustomConfirmDialog(
                                this@CreateGroupActivity,
                                "你确定要移除 ${item.name} 吗?",
                                object : CustomDialogHelper.NativeDialogCallback {
                                    override fun onConfirm() {
                                        mItems.remove(item)
                                        notifyItemRemoved(holder.absoluteAdapterPosition)
                                    }

                                    override fun onCancel() {}
                                })
                        }
                    }
                }
            binding.rvUsers.adapter = mAdapter
            val lm = binding.rvUsers.layoutManager as GridLayoutManager
            lm.spanCount = if (isTablet()) 6 else 4
        } else {
            mAdapter!!.setNewInstance(mItems)
        }
    }

    private fun onAddClick() {
        val db = DialogAddPeopleBinding.inflate(layoutInflater)
        val dialog = CustomDialogHelper.showCustomDialog(this, db.root, false)
        db.btnCamera.setOnClickListener {
            val avatar = AVATAR_LIST.random()
            db.ivAvatar.tag = avatar
            GlideStaticUtils.displayCircleImage(avatar, R.mipmap.friend_add, db.ivAvatar)
        }
        db.btnAlbum.setOnClickListener {
            val avatar = AVATAR_LIST.random()
            db.ivAvatar.tag = avatar
            GlideStaticUtils.displayCircleImage(avatar, R.mipmap.friend_add, db.ivAvatar)
        }
        db.btnCancel.setOnClickListener {
            CustomDialogHelper.dismissDialog(dialog)
        }
        db.btnOk.setOnClickListener {
            // check
            val tag = db.ivAvatar.tag
            if (tag == null) {
                showToast("请选择头像...")
                return@setOnClickListener
            }
            val avatar: String? = db.ivAvatar.tag as String
            if (avatar.isNullOrEmpty()) {
                showToast("请选择头像...")
                return@setOnClickListener
            }
            val name: String = db.etName.text.toString()
            if (name.isEmpty()) {
                showToast("请输入姓名")
                return@setOnClickListener
            }

            CustomDialogHelper.dismissDialog(dialog)
            addPeople(avatar, name)
        }

        if (BuildConfig.DEBUG) {
            db.btnCamera.performClick()
            db.etName.setText(RandomNameProvider.getName())

            lifecycleScope.launch(Dispatchers.Main) {
                delay(100)
                db.btnOk.performClick()
            }
        }
    }

    private fun addPeople(avatar: String, name: String) {
        val bean = LuckyPeople(TYPE_USER_NORMAL)
        bean.name = name
        bean.avatar = avatar
        addPeople(bean)
    }

    private fun addPeople(bean: LuckyPeople) {
        val size = mItems.size
        bean.rank = size
        mItems.add(size - 1, bean)
        mAdapter?.notifyItemRangeChanged(size - 1, 2)
    }

    override fun initView() {
        initData()
    }

    override fun hideLoading() {
        super.hideLoading()
        binding.loadingLayout.visibility = View.GONE
    }

    override fun addOnClickListener() {
        binding.toolbar.ivToolbarBack.setOnClickListener { onBackPressed() }

        binding.toolbar.tvToolbarRight.setOnClickListener {
            onSaveGroup()
        }
        if (isModify()) {
            binding.btnDeleteGroup.visibility = View.VISIBLE
            binding.btnDeleteGroup.setOnClickListener {
                CustomDialogHelper.showCustomConfirmDialog(
                    this@CreateGroupActivity,
                    "你确定要删除该分组吗?",
                    object : CustomDialogHelper.NativeDialogCallback {
                        override fun onConfirm() {
                            GroupDataCache.removeById(mGroupId, true)
                            killMyself()
                        }

                        override fun onCancel() {}
                    })
            }
        }
    }

    private fun onSaveGroup() {
        if (mItems.size <= 1) {
            showToast("请至少添加1位成员")
            return
        }
        val db = DialogSaveGroupBinding.inflate(layoutInflater)
        val dialog = CustomDialogHelper.showCustomDialog(this, db.root, false)
        db.btnCancel.setOnClickListener {
            CustomDialogHelper.dismissDialog(dialog)
        }
        db.btnOk.setOnClickListener {
            // check
            val name: String = db.etName.text.toString().trim()
            if (name.isEmpty()) {
                showToast(db.etName.hint as String?)
                return@setOnClickListener
            }
            val desc: String = db.etDesc.text.toString().trim()
            CustomDialogHelper.dismissDialog(dialog)
            saveGroup(name, desc)
        }
        if (isModify()) {
            db.etName.setText(mGroup.name)
            db.etDesc.setText(mGroup.desc)
        }
    }

    private fun saveGroup(name: String, desc: String) {
        val group = GroupEntity()
        if (isModify()) {
            group.id = mGroupId
        }
        group.name = name
        group.desc = desc
        mItems.removeLast()
        group.list = mItems
        GroupDataCache.addGroup(group, isModify())
        killMyself()
    }

    private lateinit var addResultLauncher: ActivityResultLauncher<Intent>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // registerForActivityResult  注:必须在onCreate内注册，有点劝退的感觉
        addResultLauncher =
            registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
                if (it.resultCode == Activity.RESULT_OK) {
                    val user: LuckyPeople? = it.data?.getSerializableExtra("USER") as LuckyPeople?
                    if (user != null) {
                        addPeople(user)
                    }
                }
            }
    }
}